<template>
    <div class="w-full h-full bg-gray-50 flex flex-col">
        <!-- 搜索表单区域 -->
        <div class="p-6 bg-white shadow-sm mb-6">
            <DynamicForm :fields="formFields" @submit="handleSearch" />
        </div>

        <!-- 卡片列表区域 -->
        <div class="w-full px-6 flex-1 overflow-auto custom-scrollbar">
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
                <el-card v-for="item in orderData" :key="item.orderNumber" class="order-card">
                    <template #header>
                        <div class="flex justify-between items-center text-gray-700">
                            <span class="font-medium">订单号：{{ item.orderNumber }}</span>
                            <span class="px-3 py-1 rounded-md text-sm" :class="getStatusClass(item.orderState)">{{
                                orderstate(item.orderState) }}</span>
                        </div>
                    </template>

                    <div class="card-content">
                        <div class="info-row">
                            <span class="label">手机号:</span>
                            <span class="value">{{ item.alipayPhone }}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">饰品数量:</span>
                            <span class="value">{{ item.number }}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">总金额:</span>
                            <span class="value">¥{{ item.orderTotalPrice }}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">支付宝交易号:</span>
                            <span class="value">{{ item.alipayTradeNo || '-' }}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">创建时间:</span>
                            <span class="value">{{ item.createTime }}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">最低还款日期:</span>
                            <span class="value">{{ item.minRepaymentTime || '-' }}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">打款时间:</span>
                            <span class="value">{{ item.paymentTime || '-' }}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">用户还款日期:</span>
                            <span class="value">{{ item.userRepaymentTime || '-' }}</span>
                        </div>
                        <div class="info-row">
                            <span class="label">保管费:</span>
                            <span class="value">¥{{ item.totalStorageFee }}</span>
                        </div>
                    </div>

                    <div class="mt-4 text-right space-x-2">
                        <!-- 查看详情按钮 - 始终显示 -->
                        <el-button type="primary" @click="chakanxingqing(item.orderNumber)">
                            查看详情
                        </el-button>
                        <!-- 付款按钮 - 仅在订单状态为5或8时显示 -->
                        <el-button v-if="[5, 8].includes(item.orderState)" type="success" @click="handlePayment(item)">
                            还款
                        </el-button>
                        <!-- 撤销按钮 - 仅在订单状态为1或2时显示 -->
                        <el-button v-if="[1, 2, 3].includes(item.orderState)" type="danger"
                            @click="confirmCancel(item)">
                            撤销
                        </el-button>
                        <el-button :loading="transferLoading === item.orderNumber" v-if="[2].includes(item.orderState)"
                            type="primary" @click="handleTransfer(item)">
                            开始转移
                        </el-button>
                    </div>
                </el-card>
            </div>
        </div>

        <!-- 分页区域 -->
        <div class="flex justify-center py-6 bg-white mt-6">
            <el-pagination v-model:current-page="page.pageNum" v-model:page-size="page.pageSize" :total="page.total"
                :page-sizes="[10, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </div>


    <el-dialog v-model="paymentDialogVisible" title="订单还款" width="460px" :close-on-click-modal="false" destroy-on-close>
        <div class="space-y-4 py-4">
            <div class="flex justify-between items-center py-3 border-b border-gray-100">
                <span class="text-gray-600 text-sm">抵押总金额</span>
                <span class="text-gray-800 font-medium">¥{{ currentOrder?.orderTotalPrice || 0 }}</span>
            </div>
            <div class="flex justify-between items-center py-3 border-b border-gray-100">
                <span class="text-gray-600 text-sm">保管费</span>
                <span class="text-gray-800 font-medium">¥{{ currentOrder?.totalStorageFee || 0 }}</span>
            </div>
            <div class="flex justify-between items-center py-3 border-b border-gray-100">
                <span class="text-gray-600 text-sm">逾期额外服务费</span>
                <span class="text-gray-800 font-medium">¥{{ currentOrder?.overdueAmount || 0 }}</span>
            </div>
            <div class="flex justify-between items-center py-4 mt-4 border-t border-gray-200">
                <span class="text-gray-800 text-base font-semibold">付款总金额</span>
                <span class="text-red-500 text-lg font-semibold">¥{{ getTotalAmount }}</span>
            </div>
        </div>
        <template #footer>
            <div class="flex justify-end space-x-3 pt-4">
                <el-button @click="paymentDialogVisible = false">取 消</el-button>
                <el-button type="primary" :loading="paymentLoading" @click="confirmPayment">确认支付</el-button>
            </div>
        </template>
    </el-dialog>
</template>



<script lang="ts" setup>
definePageMeta({
    title: '订单记录',
    showInMenu: true, // 控制该页面是否在菜单中显示
    requiresAuth: true, // 控制该页面是否需要登录
    icon: 'icon-dingdanjilu'
});
const router = useRouter()
const { showLoading, hideLoading } = useLoading()
// 添加新的响应式变量
const transferLoading = ref<string | number | null>(null)
const paymentLoading = ref(false)
const paymentDialogVisible = ref(false)
const currentOrder = ref<any>(null)
const orderData = ref<any[]>([])
const page = reactive({
    pageSize: 10,
    pageNum: 1,
    total: 0
})
showLoading()
const { data: initialData } = await useCustomFetch<{
    data: {
        list: any[]
        total: number
    }
}>('/api/order/list', {
    method: 'POST',
    withToken: true,
    body: {
        ...page
    }
})
hideLoading()
if (initialData.value?.data) {
    orderData.value = initialData.value.data.list
    page.total = initialData.value.data.total
}


async function fetchOrderList(filters?: any) {
    try {
        showLoading()
        const data = await customFetch<{
            data: {
                list: any[]
                total: number
            }
        }>('/api/order/list', {
            method: 'POST',
            withToken: true,
            body: {
                ...page,
                startDatetime: filters?.dateRange?.[0] || '',
                endDatetime: filters?.dateRange?.[1] || '',
                orderState: filters?.orderState || ''
            }
        })
        if (data?.data) {
            orderData.value = data.data.list
            page.total = data.data.total
        }
    } catch (error) {
        console.error('Failed to fetch order list:', error)
    } finally {
        hideLoading()
    }
}

const handleSearch = (data: any) => {
    console.log('搜索数据：', data)
    fetchOrderList(data)
}
// 添加分页处理函数
const handleSizeChange = async (val: number) => {
    page.pageSize = val
    await fetchOrderList()
}

const handleCurrentChange = async (val: number) => {
    page.pageNum = val
    await fetchOrderList()
}

const handlePayment = (orderNumber: number | string) => {
    // 处理付款逻辑
    currentOrder.value = orderNumber
    paymentDialogVisible.value = true
    console.log('Payment for order:', orderNumber)
}

// 添加计算总金额的计算属性
const getTotalAmount = computed(() => {
    if (!currentOrder.value) return 0
    const total = (currentOrder.value.orderTotalPrice || 0) +
        (currentOrder.value.totalStorageFee || 0) +
        (currentOrder.value.overdueAmount || 0)
    return total.toFixed(2)
})

// 添加确认支付函数
const confirmPayment = async () => {
    // TODO: 实现支付逻辑
    try {
        paymentLoading.value = true
        const response = await customFetch<{
            data: string
        }>('/api/order/repayment', {
            method: 'POST',
            withToken: true,
            body: currentOrder.value,
            isLoading: false
        })
        console.log(response);
        if (response.data === 'success') {
            ElMessage({
                type: 'success',
                message: '还款成功',
            })
            await fetchOrderList()
        } else {
            $message(response.data, 'warning')
        }
    } catch (error) {
        $message('付款失败', 'warning')
    } finally {
        paymentLoading.value = false
        paymentDialogVisible.value = false
    }
}



// 新增确认取消函数
const confirmCancel = async (item: any) => {
    const confirmed = await showConfirm({
        message: '确定要撤销该订单吗？'
    })
    if (!confirmed) return

    try {
        const response = await customFetch<{
            data: string
        }>('/api/order/cancelOrder', {
            method: 'POST',
            withToken: true,
            body: item,
            isLoading: false
        })
        if (response.data === 'success') {
            ElMessage({
                type: 'success',
                message: '订单已撤销',
            })
            await fetchOrderList()
        } else {
            ElMessage({
                type: 'error',
                message: '订单撤销失败',
            })
        }
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '操作失败',
        })
    }
}
const handleTransfer = async (item: any) => {
    const confirmed = await showConfirm({
        message: '确定要开始转移该订单的饰品吗？'
    })
    if (!confirmed) return
    try {
        transferLoading.value = item.orderNumber
        const response = await customFetch<{
            data: string
        }>('/api/order/transferCosmetic', {
            method: 'POST',
            withToken: true,
            body: item,
            isLoading: false
        })
        if (response.data === 'success') {
            ElMessage({
                type: 'success',
                message: '饰品转移已开始',
            })
            await fetchOrderList()
        } else {
            ElMessage({
                type: 'error',
                message: '饰品转移失败',
            })
        }
    } catch (error) {
        ElMessage({
            type: 'error',
            message: '操作失败',
        })
    } finally {
        transferLoading.value = null
    }
}


const chakanxingqing = (number: number | string) => {
    return router.push({ path: '/Jewelry', query: { orderNumber: number } })
}


const formFields = [
    {
        label: '订单状态',
        type: 'select',
        model: 'orderState',
        placeholder: '请选择订单状态',
        options: [
            { label: '全部', value: '' },
            { label: '待审核', value: 1 },
            { label: '已审核', value: 2 },
            { label: '审核不通过', value: 3 },
            { label: '饰品已转移', value: 4 },
            { label: '抵押中', value: 5 },
            { label: '已发起还款', value: 6 },
            { label: '已完成', value: 7 },
            { label: '已逾期', value: 8 },
        ]
    },
    {
        label: '日期范围',
        type: 'daterange',
        model: 'dateRange',
        placeholder: '选择日期范围',
        props: {
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            format: 'YYYY-MM-DD',
            valueFormat: 'YYYY-MM-DD'
        }
    }
];

function orderstate(state: number) {
    switch (state) {
        case 1:
            return '待审核';
        case 2:
            return '已审核';
        case 3:
            return '审核不通过';
        case 4:
            return '饰品已转移';
        case 5:
            return '抵押中';
        case 6:
            return '已发起还款';
        case 7:
            return '已完成';
        case 8:
            return '已逾期';
        case 9:
            return '已撤销';
        default:
            return '未知状态';
    }
}
function getStatusClass(state: number) {
    switch (state) {
        case 1: // 待审核
            return 'bg-blue-100 text-blue-600';
        case 2: // 已审核
            return 'bg-emerald-100 text-emerald-600';
        case 3: // 审核不通过
            return 'bg-red-100 text-red-600';
        case 4: // 饰品已转移
            return 'bg-violet-100 text-violet-600';
        case 5: // 抵押中
            return 'bg-amber-100 text-amber-600';
        case 6: // 已发起还款
            return 'bg-teal-100 text-teal-600';
        case 7: // 已完成
            return 'bg-green-100 text-green-600';
        case 8: // 已逾期
            return 'bg-rose-100 text-rose-600';
        case 9: // 已撤销
            return 'bg-slate-100 text-slate-600';
        default: // 未知状态
            return 'bg-gray-100 text-gray-600';
    }
}
</script>

<style scoped>
.order-card {
    height: auto;
    transition: all 0.3s ease;
}

.order-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.status-badge {
    padding: 4px 12px;
    border-radius: 4px;
    background-color: #e5e7eb;
    font-size: 0.875rem;
    color: #374151;
}

.card-content {
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.info-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 4px 0;
    border-bottom: 1px dashed #e5e7eb;
}

.label {
    color: #6b7280;
    font-size: 0.875rem;
}

.value {
    color: #111827;
    font-weight: 500;
}

/* 确保卡片在小屏幕上也能正常显示 */
@media (max-width: 640px) {
    .grid {
        grid-template-columns: 1fr;
    }
}
</style>
